class Message{
	friend class Folder;
public:
	explicit Message(const std::string &str = ""):contents(str){ }
	Message(const Message&);
	Message& operator=(const Message&);
	~Message();
	void save(Folder&);
	void remove(Folder&);
private:
	std::string contents;
	std::set<Folder*> folders;
	void add_to_Folders(const Message&);
	void remove_from_Folders();
};

// save和remove成员
void Message::save(Folder &f)
{
	folders.insert(&f); //将Folder f插入到Folder列表中
	f.addMsg(this);		//将message添加到Folder f的message集合中
}
void Message::remove(Folder &f)
{
	folders.erase(&f);	//将f从Folder的列表中删除
	f.remMsg(this);		//将message从f的message集合中删除
}

//拷贝控制成员
void Message::add_to_Folders(const Message &m)
{
	for(auto f : m.folders) 
		f->addMsg(this);
}

Message::Message(const Message &m):contents(m.contents),folders(m.folders)
{
	add_to_Folders(m);
}

//析构函数
void Message::remove_from_Folders()
{
	for(auto f : folders)
		f->remMsg(this);
}

Message::~Message()
{
	remove_from_Folders();
}

//拷贝赋值运算符
Message& Message::operator=(const Message &rhs)
{
	remove_from_Folders();
	contents = rhs.contents;
	folders = rhs.folders;
	add_to_Folders(rhs);
	return *this;
}

//swap函数
void swap(Message &lhs, Message &rhs)
{
	using std::swap;
	for(auto f: lhs.folders)
		f->remMsg(&lhs);
	for(auto f: rhs.folders)
		f->remMsg(&rhs)
	swap(lhs.folders,rhs.folders);
	swap(lhs.contents,rhs.contents);
	for(auto f: lhs.folders)
		f->addMsg(&lhs);
	for(auto f: rhs.folders)
		f->addMsg(&rhs);
}